package com.wang.tool.hook;

import com.wang.tool.util.SimpleLogUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

/**
 * spring静态工具
 */
public class SpringContextUtil implements AppHook {

    /**
     * app
     */
    private static ApplicationContext context;

    /**
     * 现根据类型取,再根据首字母小写获取
     *
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> type) {
        if (context == null) {
            throw new UnsupportedOperationException("app is not available");
        }
        //优先按type查
        try {
            return context.getBean(type);
        } catch (Exception ignore) {
        }
        String simpleName = type.getSimpleName();
        //首字母小写
        simpleName = Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
        return (T) context.getBean(simpleName);
    }

    /**
     * 根据名称取
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        if (context == null) {
            throw new UnsupportedOperationException("app is not available");
        }
        return context.getBean(name);
    }

    /**
     * 根据名+类型取
     *
     * @param name
     * @param requiredType
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        if (context == null) {
            throw new UnsupportedOperationException("app is not available");
        }
        return context.getBean(name, requiredType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.context = applicationContext;
        SimpleLogUtil.info("SpringContextUtil.context is init");
    }


    public static ApplicationContext getContext() {
        return context;
    }
}
